package com.lagou.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import util.MonitorWaterLineCalculator;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Activate(group = {CommonConstants.PROVIDER})
public class DubboInvokeFilter implements Filter, Runnable {

    private MonitorWaterLineCalculator monitorWaterLineCalculator90;
    private MonitorWaterLineCalculator monitorWaterLineCalculator99;

    public DubboInvokeFilter() {
        monitorWaterLineCalculator90 = new MonitorWaterLineCalculator(90);
        monitorWaterLineCalculator99 = new MonitorWaterLineCalculator(99);
        // 每隔5s打印一次最近1分钟内每个方法的TP90、TP99的耗时情况
        Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(this, 1, 5, TimeUnit.SECONDS);
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        System.out.println("==DubboInvokeFilter start...");
        long startTime = System.currentTimeMillis();
        // 执行方法
        Result result = invoker.invoke(invocation);
        long time = System.currentTimeMillis() - startTime;
        System.out.println("==invoke time:" + time + "毫秒");
        monitorWaterLineCalculator90.accumulate(time);
        monitorWaterLineCalculator99.accumulate(time);
        return result;
    }

    @Override
    public void run() {
        System.out.println("=========================统计ing...");
        double result90 = monitorWaterLineCalculator90.getResult();
        System.out.println("==TP90 result:" + result90);
        double result99 = monitorWaterLineCalculator99.getResult();
        System.out.println("==TP99 result:" + result99);
    }

}
